/*
 * ========================================================
 * Copyright(c) 2014 杭州龙骞科技-版权所有
 * ========================================================
 * 本软件由杭州龙骞科技所有, 未经书面许可, 任何单位和个人不得以
 * 任何形式复制代码的部分或全部, 并以任何形式传播。
 * 公司网址
 * http://www.hzdracom.com/
 * ========================================================
 */
package com.shwread.android.ui.page.chat;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw.activity.CommonWebActivity;
import com.shwread.android.qysw.activity.ContactGroupActivity;
import com.shwread.android.qysw.activity.ContactSearchActivity;
import com.shwread.android.qysw.activity.MainActivity;
import com.shwread.android.qysw10000152.R;
import com.shwread.android.ui.customview.MyExpandableListView;
import com.shwread.android.ui.page.AbstractUIPage;
import com.shwread.android.ui.page.chat.adapter.ContactGroupAdapter;
import com.shwread.android.ui.widget.refresh.PullToRefreshScrollView;
import com.shwread.android.ui.widget.refresh.PullToRefreshUtil;
import com.shwread.android.ui.widget.refresh.base.PullToRefreshBase;
import com.shwread.android.ui.widget.refresh.base.PullToRefreshBase.OnRefreshListener;
import com.shwread.http.ActionHelp;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.shwread.http.util.Logger;
import com.tgx.tina.android.ipc.framework.IUIPage;

import org.apache.http.Header;
import org.geometerplus.android.util.QyreaderPerferencesUtil;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import base.tina.core.task.infc.ITaskResult;
import logic.bean.AddressBookInfo;
import logic.bean.ContactYellowPageInfo;
import logic.bean.ContractInfo;
import logic.bean.GroupBean;
import logic.constants.DefaultConsts;
import logic.dao.AddressBookInfoDao;
import logic.dao.GroupDao;


/**
 * @Project： qysw_1.1.6_association
 * @Title：ContactsPage
 * @Description：
 * @Author：wayne
 * @Date：2015年11月27日上午12:10:43
 */
public class ContactsPage
        extends
        AbstractUIPage<MainActivity>
        implements
        OnClickListener
{
	public static ContactsPage                     instance;
	public static int[]                            isClose;
	private PullToRefreshScrollView                contentView;
	private MyExpandableListView                   listView;
	private TextView                               tvSearch;
	private RelativeLayout                         rlChatGroup, rlYellowPage;
	private List<GroupBean>                        groups   = new ArrayList<GroupBean>();
	private HashMap<String, List<AddressBookInfo>> contacts = new HashMap<String, List<AddressBookInfo>>();
	private String                                 ypUrl;
	private static long                            lastTimeStamp;
	
	private ContactGroupAdapter                    adapter;
	
	//数据库相关
	private GroupDao                               groupDao;
	private AddressBookInfoDao                     addressBookInfoDao;
	
	public ContactsPage(MainActivity t) {
		super(t);
	}
	
	public static ContactsPage getInstance(MainActivity t) {
		if (instance == null) instance = new ContactsPage(t);
		return instance;
	}
	
	@Override
	public <E extends Activity> View createView(E arg0, int arg1) {
		if (null != curMyView) return curMyView;
		curMyView = bActivity.getLayoutInflater().inflate(R.layout.chat_contact, null);
		//		String str = String.valueOf(System.currentTimeMillis());
		//		lastTimeStamp = Long.parseLong(str);
		groupDao = GroupDao.getInstance(bActivity);
		addressBookInfoDao = AddressBookInfoDao.getInstance(bActivity);
		lastTimeStamp = QyreaderPerferencesUtil.getInstance(context, "0").getContactLastTimeStamp();
		findView();
		initData();
		setListener();
		return curMyView;
	}
	
	//	public void goContactInfomation(AddressBookInfo info) {
	//		Intent intent = new Intent(context, ChatPersonalInfoActivity.class);
	//		intent.putExtra("contactInfo", (Serializable) info);
	//		bActivity.startActivity(intent);
	//	}
	
	private void initData() {
		ActionHelp.qryEnterpriseAddressBookList(context, lastTimeStamp, new GetAddressBookListHandler());
		ActionHelp.qryEnterpriseYellowPage(context, new GetYellowPageHandler());
	}
	
	public class GetYellowPageHandler
	        extends
	        ObjectHttpResponseHandler<ContactYellowPageInfo>
	{
		
		@Override
		public Type getType() {
			return new TypeToken<ContactYellowPageInfo>()
			{
			}.getType();
		}
		
		@Override
		public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
			
		}
		
		@Override
		public void onSuccess(int arg0, Header[] arg1, ContactYellowPageInfo arg2, String arg3) {
			if (arg2 != null)
			{
				ypUrl = arg2.getUrl();
			}
		}
	}
	
	public class GetAddressBookListHandler
	        extends
	        ObjectHttpResponseHandler<ContractInfo>
	{
		
		@Override
		public Type getType() {
			return new TypeToken<ContractInfo>()
			{
			}.getType();
		}
		
		@Override
		public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
		}
		
		@Override
		public void onSuccess(int arg0, Header[] arg1, ContractInfo arg2, String arg3) {
			if (arg2 != null)
			{
				groups = arg2.getGroupList();
				lastTimeStamp = arg2.getLastTimeStamp();
				Logger.d("group size:" + groups.size());
			}
			QyreaderPerferencesUtil.getInstance(context, "0").setContactLastTimeStamp(lastTimeStamp);
			putDataToDB();
			getDataFromDb();
			sortGroups();
			sortContacts();
			int p = 0;
			isClose = new int[groups.size()];
			for (GroupBean group : groups)
			{
				contacts.put(group.getName(), group.getAddressBookList());
				isClose[p] = 0;
				p++;
			}
			
			adapter = new ContactGroupAdapter(context, listView, groups, contacts);
			listView.setAdapter(adapter);
			
			//默认展开
			//			int groupCount = adapter.getGroupCount();
			//			for (int i = 0; i < groupCount; i++)
			//			{
			//				listView.expandGroup(i);
			//			}
			//设置点击事件
			//			listView.setOnGroupClickListener(new OnGroupClickListener()
			//			{
			//				
			//				@Override
			//				public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
			//					return true;
			//				}
			//			});
			listView.setGroupIndicator(null);
			listView.setFocusable(false);
			listView.setFocusableInTouchMode(false);
			contentView.onRefreshComplete();
			listView.setVisibility(View.VISIBLE);
			//			adapter.notifyDataSetChanged();
			//			Utils.setExpandableListViewHeightBasedOnChildren(listView, adapter);
		}
		
	}
	
	private void sortContacts() {
		List<AddressBookInfo> contacts = new ArrayList<AddressBookInfo>();
		AddressBookInfo contact = new AddressBookInfo();
		for (GroupBean group : groups)
		{
			contacts = group.getAddressBookList();
			for (int i = 0; i < contacts.size() - 1; i++)
			{
				for (int j = i; j < contacts.size(); j++)
				{
					if (contacts.get(i).getSortNum() > contacts.get(j).getSortNum())
					{
						contact = contacts.get(i);
						contacts.set(i, contacts.get(j));
						contacts.set(j, contact);
					}
				}
			}
			group.setAddressBookList(contacts);
		}
	}
	
	private void sortGroups() {
		GroupBean bean = new GroupBean();
		for (int i = 0; i < groups.size() - 1; i++)
		{
			for (int j = i + 1; j < groups.size(); j++)
			{
				if (groups.get(i).getSortNum() > groups.get(j).getSortNum())
				{
					bean = groups.get(i);
					groups.set(i, groups.get(j));
					groups.set(j, bean);
				}
			}
		}
	}
	
	private void getDataFromDb() {
		groups.clear();
		List<GroupBean> dbGroups = new ArrayList<GroupBean>();
		dbGroups = groupDao.getAll();
		for (int i = 0; i < dbGroups.size(); i++)
		{
			List<AddressBookInfo> addressBookList = new ArrayList<AddressBookInfo>();
			List<AddressBookInfo> dbList = new ArrayList<AddressBookInfo>();
			dbList = addressBookInfoDao.getListByGroupId(dbGroups.get(i).getGroupId());
			for (AddressBookInfo info : dbList)
			{
				if (info.getIsDelete().equals("n"))
				{
					addressBookList.add(info);
				}
			}
			dbGroups.get(i).setAddressBookList(addressBookList);
		}
		for (GroupBean group : dbGroups)
		{
			if (group.getAddressBookList() != null && group.getAddressBookList().size() != 0)
			{
				groups.add(group);
			}
		}
	}
	
	private void putDataToDB() {
		//		groupDao.addList(groups);
		for (GroupBean group : groups)
		{
			if (groupDao.getById(group.getGroupId()) != null)
			{
				groupDao.update(group);
			}
			else
			{
				groupDao.add(group);
			}
			for (AddressBookInfo addressBookInfo : group.getAddressBookList())
			{
				if (addressBookInfoDao.getById(addressBookInfo.getContactId(), group.getGroupId()) != null)
				{
					addressBookInfoDao.update(addressBookInfo);
				}
				else
				{
					addressBookInfoDao.add(addressBookInfo);
				}
			}
			//			addressBookInfoDao.addList(group.getAddressBookList());
		}
	}
	
	private void setListener() {
		rlYellowPage.setOnClickListener(this);
		rlChatGroup.setOnClickListener(this);
		tvSearch.setOnClickListener(this);
		contentView.setOnRefreshListener(new OnRefreshListener<ScrollView>()
		{
			
			@Override
			public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
				if (contentView.isHeaderShown())
				{
					refrush();
				}
				else if (contentView.isFooterShown())
				{
					contentView.onRefreshComplete();
				}
			}
			
		});
	}
	
	/**
	 * 下拉刷新
	 */
	private void refrush() {
		listView.setVisibility(View.GONE);
		initData();
	}
	
	private void findView() {
		contentView = (PullToRefreshScrollView) curMyView.findViewById(R.id.contact_psview);
		PullToRefreshUtil.initLabel(bActivity, contentView);
		tvSearch = (TextView) curMyView.findViewById(R.id.et_contact_search);
		rlChatGroup = (RelativeLayout) curMyView.findViewById(R.id.rl_chat_groups);
		rlYellowPage = (RelativeLayout) curMyView.findViewById(R.id.rl_chat_yellow_page);
		listView = (MyExpandableListView) curMyView.findViewById(R.id.contacts_list);
		
	}
	
	@Override
	public int enter(IUIPage<?> arg0) {
		//		initData();
		SessionPage.isFirstIn = 1;
		return 0;
	}
	
	@Override
	public int leave(IUIPage<?> arg0) {
		return 0;
	}
	
	@Override
	public void notifyView(int arg0, Bundle arg1) {
		
	}
	
	@Override
	public void setStatus(int arg0) {
		
	}
	
	@Override
	public View updateView(int arg0, ITaskResult arg1) {
		return null;
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.rl_chat_yellow_page:
				Intent ypIntent = new Intent(bActivity, CommonWebActivity.class);
				ypIntent.putExtra(DefaultConsts.title_s, "电话黄页");
				ypIntent.putExtra(DefaultConsts.req_url_s, ypUrl);
				bActivity.startActivity(ypIntent);
				break;
			
			case R.id.rl_chat_groups:
				Intent groupIntent = new Intent(bActivity, ContactGroupActivity.class);
				groupIntent.putExtra("fromType", "contactList");
				//				Intent groupIntent = new Intent(bActivity, ContactMainActivity.class);
				bActivity.startActivity(groupIntent);
				break;
			case R.id.et_contact_search:
				Intent searchIntent = new Intent(bActivity, ContactSearchActivity.class);
				bActivity.startActivity(searchIntent);
				break;
			default:
				break;
		}
	}
}
